<template>
  <div>
    <h1>飞书扫码登录--第三方授权登录</h1>
    <hr />

    <div id="login_container"></div>

    <div v-if="userInfo.picture" class="result-box">
      <div>
        <img v-if="userInfo.picture" :src="userInfo.picture" width="60px" />
      </div>
      <p>{{ userInfo.name }}</p>
      <p>登录成功！</p>
    </div>
  </div>
</template>

<script>
// 配置数据
var domain = "http://jdj8fq.natappfree.cc/";  // 这里要改：这个飞书等下要重定向的地址，要改成你的
var backUrl = domain;
var config = {
  client_id: "cli_a2dc74533c78500d", // 用你的App ID替换
  client_secret: "Otm3Rk0hJGMpwO2lLOgh5e0rIrx7epHh", // 用你的App Secret
  redirect_uri: backUrl,
};
let origin = window.location.origin;

export default {
  data() {
    return {
      userInfo: {
        picture: "",
        name: "sdf",
      },
    };
  },
  mounted() {
    let params = this.getUrlParams();
    console.log("params", params);
    // 如果url上面有code参数，就表示用户扫码成功了
    if (params && params.code) {
      // 获取token https://open.feishu.cn/document/common-capabilities/sso/api/get-access_token
      let form = {
        grant_type: "authorization_code",
        client_id: config.client_id,
        client_secret: config.client_secret,
        code: params.code,
        redirect_uri: config.redirect_uri,
      };
      this.getToken(form);
    } else {
      // 页面刚进来，url上面还没有code参数，就要拉起二维码
      this.getQrCode();
    }
  },
  methods: {
    getQrCode() {
      console.log("-------调起扫码----");

      // 调起扫码
      var goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}&response_type=code&state=state123456`;

      // 利用前端网页跳转
      // window.location.href = url;
      var QRLoginObj = QRLogin({
        id: "login_container",
        goto,
        // goto: "https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a03f23493d39d00e&redirect_uri=https%3A%2F%2Fwww.baidu.com&response_type=code&state=STATE",
        width: "300",
        height: "300",
      });
      var handleMessage = function (event) {
        console.error("event", event);
        var origin = event.origin;
        // 使用 matchOrigin 方法来判断 message 是否来自飞书页面
        if (QRLoginObj.matchOrigin(origin)) {
          var loginTmpCode = event.data;
          // 在授权页面地址上拼接上参数 tmp_code，并跳转
          window.location.href = `${goto}&tmp_code=${loginTmpCode}`;
          console.log(loginTmpCode);
        }
      };
      if (typeof window.addEventListener != "undefined") {
        window.addEventListener("message", handleMessage, false);
      } else if (typeof window.attachEvent != "undefined") {
        window.attachEvent("onmessage", handleMessage);
      }
      // 原文链接：https://blog.csdn.net/xutongbao/article/details/123278795
    },
    get_userinfo(access_token) {
      let url = "https://passport.feishu.cn/suite/passport/oauth/userinfo";
      $.ajax({
        type: "get",
        url,
        cache: false,
        async: true,
        beforeSend: function (XHR) {
          // 功能：添加自定义 HTTP 头 Authorization。
          XHR.setRequestHeader("Authorization", `Bearer ${access_token}`);
        },
        dataType: "json",
        // dataType: ($.browser.msie) ? "text" : "xml",
        success: function (data) {
          console.log("get_userinfo-成功--", data);
        },
        fail: function (err) {
          console.log("get_userinfo-err--", err);
        },
      });
    },
    getToken(form) {
      let url = origin + "/api/getfsToken";
      let that = this;
      $.ajax({
        type: "post",
        url,
        data: form,
        cache: false,
        async: true,
        beforeSend: function () {
          //等待延迟的函数
        },
        dataType: "json",
        // dataType: ($.browser.msie) ? "text" : "xml",
        success: function (data) {
          console.log("getfsToken-成功--", data);
          // 更新页面数据
          that.userInfo.picture = data.picture;
          that.userInfo.name = data.name;

          // get_userinfo(data.access_token) // 前端访问会跨域，还是需要通过后台访问
        },
        fail: function (err) {
          console.log("getfsToken-err--", err);
        },
      });
    },
    // 获取url的参数
    getUrlParams() {
      let str = window.location.search;
      console.log("str", str);
      // ?code=051YCH000vmCDN1EmM200Bdl0f3YCH0w:77 str ?
      if (str && str.includes("?") && str.includes("=")) {
        let obj = {};
        str = str.slice(1);
        console.log("str", str);
        if (str.includes("&")) {
          let arr = str.split("&");
          console.log("arr", arr);
          for (let i = 0; i < arr.length; i++) {
            let one = arr[i].split("=");
            obj[one[0]] = one[1];
          }
        } else {
          let one = str.split("=");
          obj[one[0]] = one[1];
        }
        return obj;
      }
    },
  },
};
</script>

<style>
</style>